<?php
namespace app\model;
use think\Model;
use think\model\concern\SoftDelete;
use app\model\Category as CategoryModel;
class Goods extends Model{
    protected $autoWriteTimestamp = true;
    use SoftDelete;
    protected $append = ['category_name','stock'];
    public function getCategoryNameAttr($value, $data)
    {

        try {
            $model = new CategoryModel();
           $p = $model->where('id', $data['category_id'])->find();
            return $p['name'];
        } catch (\Exception $e) {
            return show(0,$e->getMessage());
        }


    }

    //关联商品规格表
    public function space(){
        return $this->hasMany(Space::class,'goods_id');
    }
    public function getStockAttr($value,$data){
        try {
            $stock=0;
            $model= new Space();
            $res = $model->where('goods_id',$data['id'])->select();

            foreach ($res as $val){
                $stock += $val['stock'];
            }

            return $stock;
        }catch (\Exception $e){
        return  show(0,$e->getMessage());
        }

    }
}